package com.example.forum.controller;

import com.example.forum.common.AppConfig;
import com.example.forum.common.AppResult;
import com.example.forum.common.ResultCode;

import com.example.forum.model.User;
import com.example.forum.services.IUserService;
import com.example.forum.utils.MD5Util;
import com.example.forum.utils.StringUtil;
import com.example.forum.utils.UUIDUtils;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpSession;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import lombok.NonNull;



@RestController
@Slf4j
@RequestMapping("/user")
public class UserController {

    @Autowired
    private IUserService iUserService;

    @PostMapping("/register")
    public AppResult register(String username ,String nickname ,String password,String passwordRepeat){
        if(StringUtil.isEmpty(username)
                ||StringUtil.isEmpty(nickname)
                ||StringUtil.isEmpty(password)
                ||StringUtil.isEmpty(passwordRepeat)){
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            return AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE);
        }

        //校验两尺输入的密码是否一样
        if(!password.equals(passwordRepeat)){
            log.info(ResultCode.FAILED_TWO_PWD_NOT_SAME.toString());
            return AppResult.failed(ResultCode.FAILED_TWO_PWD_NOT_SAME);
        }

        //开始设置加密密码以及盐
        String salt = UUIDUtils.uuid_32();
        String scartPassword = MD5Util.md5Salt(password, salt);
        User user = new User();
        user.setUsername(username);
        user.setNickname(nickname);
        user.setPassword(scartPassword);
        user.setSalt(salt);
        iUserService.createNormalUser(user);



        return AppResult.success();

    }

    @PostMapping("/login")
    public AppResult login(HttpServletRequest request, @NonNull String username , @NonNull String password){
        User user = iUserService.login(username, password);
        HttpSession session = request.getSession(true);
        session.setAttribute(AppConfig.USER_SESSION,user);

        return AppResult.success();
    }

    @GetMapping("/info")
    public AppResult<User> getUserInfo (HttpServletRequest request,@RequestParam(value = "id", required = false) Long id) {
        // 定义返回的User对象
        User user = null;
        // 根据Id的值判断User对象的获取方式
        if (id == null) {
            // 1. 如果id为空，从session中获取当前登录的用户信息
            HttpSession session = request.getSession(false);
            // 从session中获取当前登录的用户信息
            user = (User) session.getAttribute(AppConfig.USER_SESSION);
        } else {
            // 2. 如果id不为空，从数据库中按Id查询出用户信息
            user = iUserService.SelectById(id);
        }
        // 判断用户对象是否为空
        if (user == null) {
            return AppResult.failed(ResultCode.FAILED_USER_NOT_EXISTS);
        }
        // 返回正常的结果
        return AppResult.success(user);
    }

    @GetMapping("/logout")
    public AppResult logout (HttpServletRequest request) {
        // 获取session对象
        HttpSession session = request.getSession(false);
        // 判断session是否有效
        if (session != null) {
            // 打印日志
            log.info("退出成功");
            // 表示用户在登录状态，直接销毁session
            session.invalidate();
        }

        return AppResult.success("退出成功");
    }

    @PostMapping("/modifyInfo")
    public AppResult modifyInfo(HttpServletRequest request,
                                @RequestParam(required = false) String username,
                                @RequestParam(required = false)String nickname,
                                @RequestParam(required = false)Byte gender,
                                @RequestParam(required = false)String email,
                                @RequestParam(required = false)String phoneNum,
                                @RequestParam(required = false)String remark){
        //进行非空校验
        if(StringUtil.isEmpty(username)&&StringUtil.isEmpty(nickname)
                &&gender==null&&StringUtil.isEmpty(email)
                &&StringUtil.isEmpty(phoneNum)&&StringUtil.isEmpty(remark)){
            log.warn("没有输入任何内容");
            return AppResult.failed("请输⼊要修改的内容");
        }
        User update = new User();
        HttpSession session = request.getSession(false);
        User user = (User) session.getAttribute(AppConfig.USER_SESSION);

        update.setId(user.getId());
        update.setUsername(username);
        update.setNickname(nickname);
        update.setGender(gender);
        update.setEmail(email);
        update.setPhoneNum(phoneNum);
        update.setRemark(remark);
        iUserService.modifyInfo(update);

        //把最新的结果返回到session中
        user = iUserService.SelectById(user.getId());
        session.setAttribute(AppConfig.USER_SESSION,user);


        return AppResult.success(user);



    }
    @PostMapping("/modifyPwd")
    public AppResult modifyPassword(HttpServletRequest request,
                                    @NonNull String oldPassword,
                                    @NonNull String  newPassword,
                                    @NonNull String passwordRepeat){
        if(!newPassword.equals(passwordRepeat)){
            log.warn(ResultCode.FAILED_TWO_PWD_NOT_SAME.toString());
            return AppResult.failed(ResultCode.FAILED_TWO_PWD_NOT_SAME);
        }
        HttpSession session = request.getSession(false);
        User user = (User) session.getAttribute(AppConfig.USER_SESSION);
        iUserService.modifyPassword(user.getId(), newPassword,oldPassword);

        // 4. 销毁session
        if (session != null) {
            session.invalidate();
        }

        return AppResult.success();


    }

}
